package cn.whale.kill.config;

import cn.whale.kill.mq.callback.KillMsgConfirmCallback;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

import static cn.whale.basic.constants.MQConstants.*;

//rabbitMQ的配置
@Configuration
public class MQConfig {



    //定义交换机
    @Bean
    public Exchange exchangeOrder(){
        return ExchangeBuilder.topicExchange(EXCHNAGE_ORDER_KILL).durable(true).build();
    }

    //该队列中的消息需要设置ttl
    @Bean(QUEUE_ORDER_KILL)
    public Queue queueOrder(){
        return new Queue(QUEUE_ORDER_KILL,true,false,false);
    }

    //该队列中的消息需要设置ttl
    @Bean(QUEUE_ORDER_KILL_DELAY)
    public Queue queueOrderDelay(){
        Map<String,Object> map = new HashMap<>();
        map.put("x-dead-letter-exchange", EXCHNAGE_ORDER_KILL);    //过期的消息给哪个交换机的名字
        map.put("x-dead-letter-routing-key", ROUTINGKEY_QUEUE_KILL_EXPIRED);   //死信交换机把消息个哪个个routingkey
        map.put("x-message-ttl", 10000);    //队列过期时间10M
        return new Queue(QUEUE_ORDER_KILL_DELAY,true,false,false,map);
    }

    //该队列接收死信交换机转发过来的消息
    @Bean(QUEUE_ORDER_EXPIRED)
    public Queue queueExpired(){
        return new Queue(QUEUE_ORDER_EXPIRED,true);
    }

    @Bean
    public Binding queueOrderBinding(){
        return BindingBuilder.bind(queueOrder()).to(exchangeOrder()).with(ROUTINGKEY_QUEUE_KILL).noargs();
    }
    @Bean
    public Binding queueDelayBinding(){
        return BindingBuilder.bind(queueOrderDelay()).to(exchangeOrder()).with(ROUTINGKEY_QUEUE_KILL_DELAY).noargs();
    }
    @Bean
    public Binding queueExpireBinding(){
        return BindingBuilder.bind(queueExpired()).to(exchangeOrder()).with(ROUTINGKEY_QUEUE_KILL_EXPIRED).noargs();
    }



    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        return rabbitTemplate;
    }

    /*
    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory("127.0.0.1",5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        connectionFactory.setPublisherConfirms(true);
        return connectionFactory;
    }
    */

//    @Bean
//    public MessageConverter messageConverter(){
//        return new Jackson2JsonMessageConverter();
//    }


}